"""
统计显示组件
显示处理结果的统计信息
"""

from typing import Dict
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QFrame
from PySide6.QtCore import Qt

from src.config import config
from src.utils.logger import app_logger


class StatisticsDisplayWidget(QWidget):
    """
    统计显示组件类
    
    用途：
    - 显示处理结果的统计信息
    - 实时更新统计数据
    - 提供可视化的数据展示
    """
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.reset_statistics()
    
    def setup_ui(self):
        """
        设置用户界面
        """
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("处理统计")
        title_label.setAlignment(Qt.AlignCenter)
        
        # 设置标题样式
        font_family = config.get('gui.styles.font_family')
        font_size = config.get('gui.styles.font_size')
        title_label.setStyleSheet(f"font-family: {font_family}; font-size: {font_size + 2}pt; font-weight: bold;")
        
        layout.addWidget(title_label)
        
        # 分割线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        layout.addWidget(separator)
        
        # 统计数据区域
        stats_layout = QVBoxLayout()
        
        # 创建统计标签
        self.total_label = self._create_stat_label("总图像数", "0")
        self.success_label = self._create_stat_label("成功检测", "0")
        self.valid_label = self._create_stat_label("有效车牌", "0")
        self.failed_label = self._create_stat_label("失败检测", "0")
        self.avg_conf_label = self._create_stat_label("平均置信度", "0.000")
        self.avg_time_label = self._create_stat_label("平均处理时间", "0.00s")
        
        stats_layout.addWidget(self.total_label)
        stats_layout.addWidget(self.success_label)
        stats_layout.addWidget(self.valid_label)
        stats_layout.addWidget(self.failed_label)
        stats_layout.addWidget(self.avg_conf_label)
        stats_layout.addWidget(self.avg_time_label)
        
        layout.addLayout(stats_layout)
        layout.addStretch()
    
    def _create_stat_label(self, name: str, value: str) -> QWidget:
        """
        创建统计标签
        
        参数：
            name (str): 统计项名称
            value (str): 统计值
            
        返回值：
            QWidget: 统计标签组件
        """
        widget = QWidget()
        layout = QHBoxLayout(widget)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 名称标签
        name_label = QLabel(name + ":")
        name_label.setMinimumWidth(100)
        
        # 值标签
        value_label = QLabel(value)
        value_label.setAlignment(Qt.AlignRight)
        
        # 设置字体
        font_family = config.get('gui.styles.font_family')
        font_size = config.get('gui.styles.font_size')
        style = f"font-family: {font_family}; font-size: {font_size}pt;"
        
        name_label.setStyleSheet(style)
        value_label.setStyleSheet(style + " font-weight: bold;")
        
        layout.addWidget(name_label)
        layout.addWidget(value_label)
        
        # 存储值标签以便更新
        widget.value_label = value_label
        
        return widget
    
    def update_statistics(self, stats: Dict):
        """
        更新统计显示
        
        参数：
            stats (Dict): 统计数据字典
        """
        try:
            # 更新各项统计
            self.total_label.value_label.setText(str(stats.get('total_rows', 0)))
            self.success_label.value_label.setText(str(stats.get('successful_detections', 0)))
            self.valid_label.value_label.setText(str(stats.get('valid_plates', 0)))
            self.failed_label.value_label.setText(str(stats.get('failed_detections', 0)))
            
            # 格式化平均置信度
            avg_conf = stats.get('average_confidence', 0.0)
            self.avg_conf_label.value_label.setText(f"{avg_conf:.3f}")
            
            # 格式化平均处理时间
            avg_time = stats.get('average_processing_time', 0.0)
            self.avg_time_label.value_label.setText(f"{avg_time:.2f}s")
            
            # 根据数据设置颜色
            self._update_colors(stats)
            
            app_logger.debug("统计信息更新完成")
            
        except Exception as e:
            app_logger.error(f"更新统计信息失败: {e}")
    
    def _update_colors(self, stats: Dict):
        """
        根据统计数据更新颜色
        
        参数：
            stats (Dict): 统计数据字典
        """
        try:
            total = stats.get('total_rows', 0)
            success = stats.get('successful_detections', 0)
            valid = stats.get('valid_plates', 0)
            failed = stats.get('failed_detections', 0)
            
            # 计算成功率
            success_rate = (success / total * 100) if total > 0 else 0
            valid_rate = (valid / total * 100) if total > 0 else 0
            
            # 设置成功检测颜色
            if success_rate >= 80:
                success_color = "green"
            elif success_rate >= 60:
                success_color = "orange"
            else:
                success_color = "red"
            
            # 设置有效车牌颜色
            if valid_rate >= 70:
                valid_color = "green"
            elif valid_rate >= 50:
                valid_color = "orange"
            else:
                valid_color = "red"
            
            # 设置失败检测颜色
            failed_color = "red" if failed > 0 else "gray"
            
            # 应用颜色
            font_family = config.get('gui.styles.font_family')
            font_size = config.get('gui.styles.font_size')
            base_style = f"font-family: {font_family}; font-size: {font_size}pt; font-weight: bold;"
            
            self.success_label.value_label.setStyleSheet(base_style + f" color: {success_color};")
            self.valid_label.value_label.setStyleSheet(base_style + f" color: {valid_color};")
            self.failed_label.value_label.setStyleSheet(base_style + f" color: {failed_color};")
            
        except Exception as e:
            app_logger.error(f"更新统计颜色失败: {e}")
    
    def reset_statistics(self):
        """
        重置统计显示
        """
        empty_stats = {
            'total_rows': 0,
            'successful_detections': 0,
            'valid_plates': 0,
            'failed_detections': 0,
            'average_confidence': 0.0,
            'average_processing_time': 0.0
        }
        
        self.update_statistics(empty_stats)
        app_logger.debug("统计信息已重置")
    
    def get_summary_text(self, stats: Dict) -> str:
        """
        获取统计摘要文本
        
        参数：
            stats (Dict): 统计数据字典
            
        返回值：
            str: 统计摘要文本
        """
        total = stats.get('total_rows', 0)
        success = stats.get('successful_detections', 0)
        valid = stats.get('valid_plates', 0)
        failed = stats.get('failed_detections', 0)
        avg_conf = stats.get('average_confidence', 0.0)
        avg_time = stats.get('average_processing_time', 0.0)
        
        if total == 0:
            return "暂无处理结果"
        
        success_rate = (success / total * 100) if total > 0 else 0
        valid_rate = (valid / total * 100) if total > 0 else 0
        
        summary = f"""处理统计摘要:
总图像数: {total}
成功检测: {success} ({success_rate:.1f}%)
有效车牌: {valid} ({valid_rate:.1f}%)
失败检测: {failed}
平均置信度: {avg_conf:.3f}
平均处理时间: {avg_time:.2f}s"""
        
        return summary 